// Copyright tang.  All rights reserved.
// https://gitee.com/inrgihc/dbswitch
//
// Use of this source code is governed by a BSD-style license
//
// Author: tang (inrgihc@126.com)
// Date : 2020/1/2
// Location: beijing , china
/////////////////////////////////////////////////////////////
package com.gitee.jdbc.elasticsearch;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public final class JsonUtils {

  private static final Logger log = LoggerFactory.getLogger(JsonUtils.class);

  private static ObjectMapper jacksonMapper = new ObjectMapper();

  public static String toJsonString(Object object) {
    try {
      return jacksonMapper.writeValueAsString(object);
    } catch (JsonProcessingException e) {
      log.error(" convert object to json string error：{}", object.toString(), e);
      throw new RuntimeException(e);
    }
  }

  public static <T> T toBeanObject(String jsonString, Class<T> clazz) {
    try {
      return jacksonMapper.readValue(jsonString, clazz);
    } catch (JsonProcessingException e) {
      String className = clazz.getSimpleName();
      log.error(" parse json [{}] to class [{}] error：{}", jsonString, className, e);
      throw new RuntimeException(e);
    }
  }
}
